package cn.autumnorange.app.common.repository.impl;

import cn.autumnorange.app.common.entity.BaseDataEntity;
import cn.autumnorange.app.common.repository.BaseDateRepository;
import cn.autumnorange.app.common.util.ValidationUtils;

import java.sql.Timestamp;
import java.util.List;

public abstract class BaseDateRepositoryImpl<X extends BaseDataEntity> extends BaseRepositoryImpl<X>
    implements BaseDateRepository<X> {

  @Override
  public X save(X entity) {
    Timestamp timeByCreateOrUpd = new Timestamp(System.currentTimeMillis());
    setCreateParam(entity, timeByCreateOrUpd);
    setUpdParam(entity, timeByCreateOrUpd);
    super.save(entity);
    return entity;
  }

  @Override
  public X update(X entity) {
    setUpdParam(entity, new Timestamp(System.currentTimeMillis()));
    return super.update(entity);
  }

  @Override
  public boolean batchObject(List<X> entityList) {
    for (X entity : entityList) {
      String isVali = ValidationUtils.validation(entity);
      if (!isVali.equals(ValidationUtils.SUCCESS)) {
        return false;
      }
      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      if (entity.getId() != null) {
        setCreateParam(entity, timestamp);
        entityManager.persist(entity);
      } else {
        setUpdParam(entity, timestamp);
        entityManager.merge(entity);
      }
    }
    return true;
  }

  private void setCreateParam(X entity, Timestamp createTime) {
    //    UserDetailsImpl userDetails = SecurityPrincipalContext.getUserDetailsImpl();
    //    if (userDetails != null) {
    //      entity.setCreateId(userDetails.getId());
    //    }
    entity.setCreateTime(createTime);
    entity.setIsDelete(false);
    entity.setStatus(1);
    entity.setVersion(0L);
  }

  private void setUpdParam(X entity, Timestamp updTime) {
    //    UserDetailsImpl userDetails = SecurityPrincipalContext.getUserDetailsImpl();
    //    if (userDetails != null) {
    //      entity.setUpdateId(userDetails.getId());
    //    }

    entity.setUpdateTime(updTime);
  }
}
